package com.zdl.interestingapp.view.activities

import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.MotionEvent
import com.zdl.interestingapp.R
import com.zdl.interestingapp.data.ApiClient
import com.zdl.interestingapp.data.api.ApiStores
import com.zdl.interestingapp.data.api.RequestApi
import com.zdl.interestingapp.data.entity.MessageLogging
import com.zdl.interestingapp.data.model.QAndAModel
import com.zdl.interestingapp.utils.MyDateUtil
import com.zdl.interestingapp.utils.MyPhoneUtil
import com.zdl.interestingapp.utils.MyStringUtil
import com.zdl.interestingapp.view.BaseActivity
import com.zdl.interestingapp.view.adapter.QARecycleViewAdapter
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*
import org.litepal.crud.DataSupport

class MainActivity : BaseActivity() {

    private lateinit var adapter: QARecycleViewAdapter
    private var data: ArrayList<MessageLogging> = ArrayList()

    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.activity_main)
        super.onCreate(savedInstanceState)
    }

    override fun initData() {
        val layoutManager = LinearLayoutManager(this)
        //软键盘弹出，recycleView内容上移
        layoutManager.stackFromEnd = true
        recyclerView.layoutManager = layoutManager
        data.addAll(DataSupport.findAll(MessageLogging::class.java))
        adapter = QARecycleViewAdapter(data)
    }

    override fun setListener() {
        recyclerView.adapter = adapter
        btn_send.setOnClickListener{
            ask()
        }
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev?.action == MotionEvent.ACTION_DOWN) {
            if (MyPhoneUtil.isSoftInputShowing(this)) {
                if (MyPhoneUtil.isShouldHideSoftInput(input_box, ev)) {
                    MyPhoneUtil.dismissSoftInput(this)
                }
            }
            return super.dispatchTouchEvent(ev)
        }
        if (window.superDispatchTouchEvent(ev)){
            return true
        }
        return onTouchEvent(ev)
    }

    private fun ask() {
        val msg = et_msg.text.toString()
        if (MyStringUtil.isEmpty(msg)) {
            return
        } else {
            val messageLogging = MessageLogging(1, msg, MyDateUtil.getCurrentTime())
            data.add(messageLogging)
            adapter.notifyDataSetChanged()
            recyclerView.scrollToPosition(adapter.itemCount - 1)
            et_msg.text.clear()
            messageLogging.save()
        }

        val requestApi = ApiClient.retrofitBuilder().baseUrl(ApiStores.SOJSON_URL_API_SERVER).build().create(RequestApi::class.java)
        requestApi.ask("free", msg)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<QAndAModel> {
                    override fun onSubscribe(d: Disposable) {

                    }

                    override fun onNext(qAndAModel: QAndAModel) {
                        var content = qAndAModel.content
                        if (content.contains("{br}")){
                            content = content.replace("{br}", "\n")
                        }
                        val messageLogging = MessageLogging(2, content, MyDateUtil.getCurrentTime())
                        data.add(messageLogging)
                        adapter.notifyDataSetChanged()
                        recyclerView.scrollToPosition(adapter.itemCount - 1)
                        messageLogging.save()
                    }

                    override fun onError(e: Throwable) {

                    }

                    override fun onComplete() {

                    }
                })
    }
}
